import socket
import time


class TcpTimeSer:
    def __init__(self, host, port):
        self.addr = (host, port)
        self.serv = socket.socket()
        self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind(self.addr)
        self.serv.listen(2)

    def handle_client(self, cli_sock):
        "和客户端通信"
        while True:
            data = str(cli_sock.recv(1024), encoding="utf8")  # 套接字端每次接收的数据
            # if data.strip()=="":
            if not data.strip():
                break
            data = "[%s] %s" % (time.strftime("%H:%M:%d"), data)
            print(data)  # 在服务器打印
            cli_sock.sendall(bytes(data, encoding="utf-8"))
        cli_sock.close()

    def mainloop(self):
        while True:
            cli_sock, cli_addr = self.serv.accept()  # 接受C端连接
            self.handle_client(cli_sock)
            cli_sock.close()  #这行是否可以不写的
        self.serv.close()

if __name__ == '__main__':
    s = TcpTimeSer("",12345)
    s.mainloop()
